<template>
	<div class="app">
		<div class="connect">
			<div class="status">{{ connectStatus }}</div>
			<div class="connectOrDisconnect" @click="connectOrDisConnect">{{ connectButtonText }}</div>
		</div>
	</div>
</template>

<script>
export default {
	data() {
		return {
			isConnected: false,
			websocket: undefined,
		};
	},
	computed: {
		connectStatus() {
			if (this.isConnected) {
				return '已连接';
			}
			return '未连接';
		},
		connectButtonText() {
			if (!this.isConnected) {
				return '连接';
			}
			return '断开';
		},
	},
	methods: {
		/**
		 * 此方法用于新建一个WebSocket连接
		 */
		newWebSocket() {
			// 实例化一个WebSocket对象，实例化之后，会立即连接
			this.websocket = new WebSocket('ws://' + location.host + '/api/textSocket');
			// 添加各个监听事件
			this.websocket.addEventListener('open', (e) => {
				this.isConnected = true;
				console.log('已连接！');
			});
			this.websocket.addEventListener('close', (e) => {
				this.isConnected = false;
				console.log('已断开连接！');
			});
			this.websocket.addEventListener('error', (e) => {
				console.error('出现错误！');
			});
			this.websocket.addEventListener('message', (e) => {
				console.log('收到消息：' + e.data);
			});
		},
		/**
		 * 连接或者断开按钮
		 */
		connectOrDisConnect() {
			// 如果已连接则点击按钮断开连接
			if (this.isConnected) {
				// close方法关闭连接
				this.websocket.close();
			} else {
				this.newWebSocket();
			}
		},
	},
};
</script>

<style lang="scss">
.app {
	.connect {
		.connectOrDisconnect {
			width: 42px;
			height: 28px;
			line-height: 28px;
			text-align: center;
			color: white;
			background-color: blue;
			border-radius: 6px;
			cursor: pointer;
			user-select: none;

			&:hover {
				background-color: purple;
			}
		}
	}
}
</style>